<template>
  <el-dialog
    :title="roles.id?'编辑角色':'添加角色'"
    :visible="editShowDialog"
    width="50%"
    @close="handleClose"
  >
    <el-form ref="ruleForm" :model="roles" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="标题" prop="title">
        <el-input v-model="roles.title" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="roles.description" type="text" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="btnOk">确认</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { addRole, getRoleById, editRole } from '@/api/role'
export default {
  props: {
    editShowDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roles: {
        title: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {

    async btnOk() {
      try {
        await this.$refs.ruleForm.validate()
        if (this.roles.id) {
          await editRole(this.roles)
          this.$emit('getRoles')
        } else {
          await addRole(this.roles)
          this.$emit('getRoles', 'add')
        }
        this.$message.success('操作成功')
        this.handleClose()
      } catch (error) {
        console.log(error)
      }
    },
    async getRoleById(id) {
      const { data } = await getRoleById(id)
      this.roles = data
    },
    handleClose() {
      this.$refs.ruleForm.resetFields()
      this.$emit('update:editShowDialog', false)
      this.roles = {
        title: '',
        description: ''
      }
    }
  }
}
</script>

<style>

</style>
